package com.dyc.course.sys.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import com.dyc.course.common.utils.R;
import com.dyc.course.sys.entity.SysDictEntity;
import com.dyc.course.sys.repository.SysDictRepository;

import java.util.Map;
import java.util.Optional;

import javax.validation.Valid;

/**
 * 数据字典
 *
 */
@RestController
@RequestMapping("sys/dict")
public class SysDictController {
	
    @Autowired
    private SysDictRepository repository;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:dict:list")
    public R list(@RequestParam Map<String, Object> params) {
    	String page = (String) params.get("page");
		String size = (String) params.getOrDefault("limit", "10");
		String sortBy = (String) params.getOrDefault("sortBy", "id");
		Sort sort = Sort.by(sortBy);
		PageRequest pageRequest = PageRequest.of(Integer.parseInt(page)-1, Integer.parseInt(size), sort);
		Page<SysDictEntity> entities;
		if (params.containsKey("name") && params.get("name").toString().length() > 0) {
			entities = repository.findByNameLike("%" + (String) params.get("name") + "%", pageRequest);
		} else {
			entities = repository.findAll(pageRequest);
		}
        return R.ok().put("page", entities);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:dict:info")
    public R info(@PathVariable("id") Long id) {
    	Optional<SysDictEntity> optional = repository.findById(id);
    	SysDictEntity dict = null;
    	if (optional.isPresent()) {
        	dict = optional.get();
    	}
        return R.ok().put("dict", dict);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:dict:save")
    public R save(@RequestBody @Valid SysDictEntity dict){

        repository.save(dict);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:dict:update")
    public R update(@RequestBody SysDictEntity dict){

        repository.save(dict);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:dict:delete")
    public R delete(@RequestBody Long[] ids) {
    	for (Long id : ids) {
    		repository.deleteById(id);
    	}
        return R.ok();
    }

}
